package com.share.domain.credit.service;

import com.share.domain.credit.model.aggregate.TradeAggregate;
import com.share.domain.credit.model.entity.CreditAccountEntity;
import com.share.domain.credit.model.entity.CreditOrderEntity;
import com.share.domain.credit.model.entity.TradeEntity;
import com.share.domain.credit.repository.ICreditRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Slf4j
@Service
public class CreditAdjustService implements ICreditAdjustService {

    @Resource
    private ICreditRepository creditRepository;


    @Override
    public String createOrder(TradeEntity tradeEntity) {
        log.info("增加账户积分额度开始 userId:{},tradeName:{},amount:{}",tradeEntity.getUserId(),tradeEntity.getTradeName(),tradeEntity.getTradeAmount());
        //1.创建账号积分实体
        CreditAccountEntity creditAccountEntity = TradeAggregate.createCreditAccountEntity(
                tradeEntity.getUserId(),tradeEntity.getTradeAmount());

        //2.创建积分订单实体
        CreditOrderEntity creditOrderEntity = TradeAggregate.createCreditOrderEntity(
                tradeEntity.getUserId(),tradeEntity.getTradeName(),tradeEntity.getTradeType(),tradeEntity.getTradeAmount(),tradeEntity.getOutBusinessNo()
        );

        //3.构建聚合体
        TradeAggregate tradeAggregate = new TradeAggregate();
        tradeAggregate.setUserId(tradeEntity.getUserId());
        tradeAggregate.setCreditOrderEntity(creditOrderEntity);
        tradeAggregate.setCreditAccountEntity(creditAccountEntity);

        //4.保存积分交易订单
        creditRepository.saveUserCreditTradeOrder(tradeAggregate);
        log.info("增加账户积分额度完成:userId:{},orderId:{}",tradeAggregate.getUserId(),creditOrderEntity.getOrderId());

        return creditOrderEntity.getOrderId();
    }
}
